tool
extends Tree


signal select_func_node(path)


const FileUtil = preload("res://addons/function_tree/util/generate/FileUtil.gd")


var icon : Texture
var root : TreeItem
var dir = Directory.new()



#==================================================
#   内部方法
#==================================================
func _ready():
	hide_root = true

func clear():
	.clear()
	root = null



#==================================================
#   自定义方法
#==================================================
##  扫描文件路径
## 属性功能同 `add_scan` 方法
func scan(path: String, recursion: bool = true) -> bool:
	clear()
	return add_scan(path, recursion)


##  追加扫描
## @path  扫描路径
## @recursion  子路径全部扫描
## @return  返回是否添加了 Item
func add_scan(path: String, recursion: bool = true) -> bool:
	if !root:
		root = create_item()
	var data = FileUtil.scan(path, recursion)
	if data:
		update_item(data, root, path)
		return true
	return false


##  添加 Item
## @path  文件路径
## @parent_item  父级 Item
## @can_select  是否可以选择
func add_path_item(
	path: String, 
	parent_item: TreeItem = null,
	can_select : bool = true
) -> TreeItem:
	if !root:
		root = create_item()
	if parent_item == null:
		parent_item = root
	var item = create_item(parent_item)
	item.set_text(0, path.get_file().get_basename())
	item.set_metadata(0, path)
	if !can_select:
		item.set_selectable(0, false)
		item.set_custom_color(0, Color(1,1,1,0.33))
	if icon:
		item.set_icon(0, icon)
	return item

##  更新 Item 项
## @data  
## @parent  父Item
## @dir  文件夹
func update_item(data: Dictionary, parent: TreeItem, dir: String) -> void:
	var value
	for key in data:
		value = data[key]
		if value is bool:
			add_path_item(dir.plus_file(key), parent)
		elif value is Dictionary:
			var p = dir.plus_file(key)
			var item = add_path_item(p, parent, false)
			update_item(value, item, p)


## 双击 item 项时
func _on_Tree_item_activated():
	var item = get_selected()
	if item && item.get_metadata(0):
		emit_signal("select_func_node", item.get_metadata(0))


##  通过数据更新 Item 
## @data  
## @path  
func update_item_by_filename(filenames: PoolStringArray, path: String):
	clear()
	root = create_item()
	var data := {}
	for filename_ in filenames:
		data[filename_] = true
	update_item(data, root, path)

